import requests
import os
from configparser import ConfigParser
import time
import logging
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)  # 这里主要是禁用掉警告


def sr_echo(param_code=0, param_msg='', param_data=None):
    """
    自定义返回格式
    :param param_code: 返回的代码
    :param param_msg: 返回的文本信息
    :param param_data: 返回的数据
    :return:
    """
    if param_data is None:
        param_data = {}
    def_now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # return {'code': param_code, 'msg': param_msg, 'data': param_data}
    return {'code': param_code, 'msg': '[{}]'.format(def_now_time) + param_msg, 'data': param_data}


def requests_jd(param_url):
    def_headers = {
        "content-type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36"
    }
    def_params = {

    }
    try:
        def_rs = requests.get(url=param_url, params=def_params, headers=def_headers, verify=False)
    except:
        return sr_echo(-10001, '请求网页失败')
    def_rs_json_data = def_rs.json()
    # return sr_echo(rs_json_data['code'], rs_json_data['message'], rs_json_data['data'])
    return def_rs_json_data


def ftqq_send(param_sckey, param_text, param_desp):
    def_url = f'https://sc.ftqq.com/{param_sckey}.send'
    def_params = {
        'text': param_text,
        'desp': param_desp
    }
    def_rs = requests.post(url=def_url, params=def_params, verify=False)
    def_rs_json_data = def_rs.json()
    return def_rs_json_data


if __name__ == '__main__':
    # 程序根目录的绝对路么
    parent_dir = os.path.dirname(os.path.abspath(__file__))
    # 创建日志存储目录
    os.makedirs(f'{parent_dir}/log/', mode=0o777, exist_ok=True)
    # 日志基础配置
    logging.basicConfig(filename=f'{parent_dir}/log/' + time.strftime('%Y-%m-%d') + '.log', level=logging.DEBUG,
                        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S %p")
    logger = logging.getLogger(__name__)

    # 读取配置文件
    config = ConfigParser()
    config.read(f'{parent_dir}/config.cfg', encoding='utf-8')
    data = [
        {'url': config.get('api_url', 'jd_jdfactory'), 'share_code': config.get('share_code', 'jd_jdfactory')},
        {'url': config.get('api_url', 'jd_dreamfactory'), 'share_code': config.get('share_code', 'jd_dreamfactory')},
        {'url': config.get('api_url', 'jd_plantbean'), 'share_code': config.get('share_code', 'jd_plantbean')},
        {'url': config.get('api_url', 'jd_fruit'), 'share_code': config.get('share_code', 'jd_fruit')},
        {'url': config.get('api_url', 'jd_pet'), 'share_code': config.get('share_code', 'jd_pet')},
        {'url': config.get('api_url', 'jd_jdzz'), 'share_code': config.get('share_code', 'jd_jdzz')}
    ]
    success_count = 0  # 提交成功记数
    fail_count = 0  # 提交失败记数
    existed_count = 0  # 重复提交记数
    sum_count = len(data)  # 总共需要提交的
    for d in data:
        url = d['url'] + d['share_code']
        re = requests_jd(param_url=url)
        logger.info(re)
        print(re)
        try:
            if re['code'] == 200:
                success_count = success_count + 1
            elif re['code'] == 400:
                existed_count = existed_count + 1
            else:
                fail_count = fail_count + 1
        except:
            fail_count = fail_count + 1
        time.sleep(30)  # 延时30秒后再继续执行。过快请求容易封禁IP
    # 任务提交完成后，进行推送消息处理
    send_desp = f"老baby一族，温馨提示：\n- 总共：{sum_count}\n- 成功：{success_count}\n- 失败：{fail_count}\n- 存在：{existed_count}\n\n族长签字：瘫姐"
    g_f_re = ftqq_send(config.get('notification_push', 'sckey'), '提交助力结果', send_desp)
    logger.info(g_f_re)
